// todo...
// import { loadQKApp } from "../micro_apps/index";
import { mainAppRouter } from ".";
import shareds from "@/common/utils/shared";
import { MAIN_APP_NAMES } from "../micro_apps";
import store from "../store";
import { BASIC_ROUTE } from "./router.config";

const RouteUtils = {
  /** 菜单点击 */
  onMenuChange: (params) => {
    const { menu } = params;
    console.log("========onMenuChange", menu);
    if (!menu.alias) {
      // 点击应用(不是菜单的格式)
      RouteUtils.handleRouteEnterByApp({ appMenu: menu });
      return;
    }
    if (menu.url_type == "target_url") {
      window.open(menu.alias);
      return;
    }
    if (menu.url_type == "frame_url") {
      mainAppRouter.push({
        path: `/iframes/${menu.arrKey}`,
        query: {key: menu.arrKey},
      });
      return;
    }
    const isSettingMenu = store.getters.settingMenu.findIndex(
      (it) => it.alias == menu.alias
    );
    if (menu.parent_id == 0 || isSettingMenu > -1) {
      // 一级菜单(顶部菜单)
      store.dispatch("SetCurrentTopMenu", menu).then(() => {
        if (!menu.children || !menu.children.length) {
          RouteUtils.handleRouteEnterByApp({ menu });
        } else {
          // 进入加载过的菜单
          let enterMenuAlias = store.getters.loadedSubMenu[menu.alias];
          let enterMenu = null;
          if (enterMenuAlias) {
            enterMenu = RouteUtils.getMenuByAlias(
              enterMenuAlias,
              menu.children
            );
          }
          if (!enterMenu) {
            enterMenu = menu.children[0];
          }
          RouteUtils.handleRouteEnterByApp({ menu: enterMenu });
        }
      });
    } else {
      // 子菜单
      RouteUtils.handleRouteEnterByApp({ menu });
    }
  },
  /** 根据菜单所属应用转对应的跳转方法
   */
  handleRouteEnterByApp: ({ menu, enterType = "push", appMenu }) => {
    if (appMenu || !MAIN_APP_NAMES.includes(menu.app)) {
      // 跳转子应用
      const preApp = store.getters.currentApp;
      if (appMenu) {
        // 点击应用列表跳转
        store.dispatch("SetCurrentApp", appMenu).then(() => {
          if (preApp && preApp.app_micro == appMenu.app_micro) {
            mainAppRouter.push({
              name: "refresh",
              query: {
                url: encodeURIComponent(
                  `/apps/${appMenu.app_micro}/${appMenu.app_url}`
                ),
              },
            });
          } else {
            mainAppRouter.push(`/apps/${appMenu.app_micro}/${appMenu.app_url}`);
          }
        });
      } else {
        // 点击菜单跳转
        if (menu.parent_id == 0) {
          store.dispatch("SetCurrentTopMenu", menu);
        }
        store.dispatch("SetCurrentAppName", menu.app);
        // loadQKApp({
        //   appName: menu.app,
        //   pathName: menu.alias,
        //   params: menu.param ? shareds.getQueryObj(menu.param) : {},
        // });
      }
    } else {
      // 主应用跳转
      RouteUtils.mainAppRouteChange({ menu, enterType });
    }
  },
  /** 主应用路由跳转
   * enterType push|replace
   */
  mainAppRouteChange: ({ menu, enterType = "push" }) => {
    let query = menu.param ? shareds.getQueryObj(menu.param) : {};
    if (menu.url_type === 'frame_url') {
      mainAppRouter[enterType]({
        path: `/iframes/${menu.arrKey}`,
        query: {
          ...query,
          key: menu.arrKey,
        },
      });
    } else {
      mainAppRouter[enterType]({
        name: menu.alias,
        query,
      });
    }

  },
  /** 根据alias获取menu */
  getMenuByAlias: (alias, menuList) => {
    for (let item of menuList) {
      if (item.alias == alias) {
        return item;
      }
      if (item.children && item.children.length) {
        const result = RouteUtils.getMenuByAlias(alias, item.children);
        if (result) {
          return result;
        }
      }
    }
    return null;
  },
  /** 访问路径添加子应用前缀 */
  getPath: (path) => {
    let prefix = "";
    if (window.__POWERED_BY_QIANKUN__) {
      // prefix内容为主应用的activeRule
      prefix = `/apps/${defaultSetting.name}`;
    }
    path = prefix + path;
    return path;
  },
  /** 多级菜单重定向 */
  getRedirectPath: (to) => {
    // 进入第一个子菜单
    const parentRoute = to.matched[0];
    let name = parentRoute.children[0].name;
    return { name };
  },
  /** 非返回的菜单的权限 */
  handleMenuPermisson: () => {
    let result = {};
    getRoutePermisson(BASIC_ROUTE, result);
    store.dispatch("SetMenuPermisson", result);
  },
};

const getRoutePermisson = (list, result) => {
  for (let item of list) {
    if (item.meta && item.meta.permisson) {
      result[item.name] = item.meta.permisson;
    }
    if (item.children) {
      getRoutePermisson(item.children, result);
    }
  }
};

export default RouteUtils;
